// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biz.smpaa.webservice.YsIntfce;
import com.javaweb.admin.entity.YYq005;
import com.javaweb.admin.entity.YYq005Detail;
import com.javaweb.admin.entity.YgOrder;
import com.javaweb.admin.query.YgOrderQuery;
import com.javaweb.admin.service.Const;
import com.javaweb.admin.service.SQLDBQuery;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.constant.YYq007Constant;
import com.javaweb.admin.entity.YYq007;
import com.javaweb.admin.mapper.YYq007Mapper;
import com.javaweb.admin.query.YYq007Query;
import com.javaweb.admin.service.IYYq007Service;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.utils.ShiroUtils;
import com.javaweb.admin.vo.yyq007.YYq007InfoVo;
import com.javaweb.admin.vo.yyq007.YYq007ListVo;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import java.io.InputStream;
import java.io.Serializable;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.*;

/**
  * <p>
  *  服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2024-02-01
  */
@Service
public class YYq007ServiceImpl extends BaseServiceImpl<YYq007Mapper, YYq007> implements IYYq007Service {

    @Autowired
    private YYq007Mapper yYq007Mapper;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        YYq007Query yYq007Query = (YYq007Query) query;
        // 查询条件
        QueryWrapper<YYq007> queryWrapper = new QueryWrapper<>();
        // queryWrapper.orderByDesc("id");

        // 获取数据列表
        IPage<YYq007> page = new Page<>(yYq007Query.getPage(), yYq007Query.getLimit());
        IPage<YYq007> pageData = yYq007Mapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            YYq007ListVo yYq007ListVo = Convert.convert(YYq007ListVo.class, x);
            return yYq007ListVo;
        });
        return JsonResult.success(pageData);
    }


    @Override
    public List<YYq005Detail> getInvCustList(String yybm, String invcode, String invname,String zxspbm) {
        return yYq007Mapper.getCustInvList(yybm,invcode,invname,zxspbm);
    }

    @Override
    public JsonResult GetYQ007List(BaseQuery query) {
        YYq007Query ygOrderQuery = (YYq007Query) query;
        IPage<YYq007> page = new Page<>(ygOrderQuery.getPage(), ygOrderQuery.getLimit());
        IPage<YYq007> pageData = yYq007Mapper.GetYQ007List(page, ygOrderQuery);
        return JsonResult.success(pageData);

    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        YYq007 entity = (YYq007) super.getInfo(id);
        // 返回视图Vo
        YYq007InfoVo yYq007InfoVo = new YYq007InfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, yYq007InfoVo);
        return yYq007InfoVo;
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(YYq007 entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setYqbm(Const.YGPT_CORPCODE);
            entity.setThzj(entity.getThsl().multiply(entity.getThdj()).setScale(2, RoundingMode.HALF_UP));
            entity.setUpdateUser(ShiroUtils.getUserId());
            entity.setUpdateTime(DateUtils.now());
        } else {
            entity.setYqbm(Const.YGPT_CORPCODE);
            entity.setThzj(entity.getThsl().multiply(entity.getThdj()).setScale(2, RoundingMode.HALF_UP));
            entity.setCreateUser(ShiroUtils.getUserId());
            entity.setCreateTime(DateUtils.now());
        }
        return super.edit(entity);
    }


    @Override
    public JsonResult THDDTToYGPT(YYq007 dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ007.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        Element elementD = XmlUtil.getElement(elementG,"DETAIL");
        YYq007 entity = yYq007Mapper.selectById(dto.getId());

        String czlx = dto.getCzlx();
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的代填退货单号id:"+dto.getId().toString());
        }
        //判断订单编号是否已经更新
        if(!StringUtils.isEmpty(entity.getThdbh()) && "1".equals(czlx))
        {
            return JsonResult.error("代填退货单已成功上传，不能重复提交。阳光平台返回退货单编号【"+entity.getThdbh()+"】");
        }
        if(StringUtils.isEmpty(entity.getThdbh()) && "3".equals(czlx))
        {
            return JsonResult.error("代填退货单未上传，不能作废。");
        }

        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;
        Document docSubmit003 = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"CZLX",czlx);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",entity.getYybm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",entity.getPsdbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YQBM",entity.getYqbm());
        if("1".equals(czlx)) {
            CommonUtils.XmlSetNodeContent(YsPsdMain, "THDBH", "");
        }else{
            CommonUtils.XmlSetNodeContent(YsPsdMain, "THDBH", entity.getThdbh());
        }
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DLCGBZ",entity.getDlcgbz());
        String thrq = DateUtil.format(DateUtil.parse(entity.getSjthrq(),DateUtils.YYYY_MM_DD),DateUtils.YYYYMMDD);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"SJTHRQ",thrq);
        CommonUtils.XmlSetNodeContent(YsPsdMain,"SPLX",entity.getSplx());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"ZXSPBM",entity.getZxspbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"GGBZ",entity.getGgbz());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"CGJLDW",entity.getCgjldw());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"SCPH",entity.getScph());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"THSL",entity.getThsl().toString());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"THDJ",entity.getThdj().toString());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"THZJ",entity.getThzj().toString());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"SCPH",entity.getThyy());

        try {
            result = YsDDDTUpload(XmlUtil.toStr(document003, true), entity.getId());
            if ("00000".equals(result[4])) {
                return JsonResult.success();
            } else {
                return JsonResult.error(result[4]+result[5]+":"+result[6]);
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult THDDTConfirm(YYq007 dto) {
        ClassPathResource classPathResource = new ClassPathResource("nc/" + "YQ008.xml");
        InputStream inputStream039 = classPathResource.getStream();
        Document document003= XmlUtil.readXML(inputStream039);
        Element elementG=XmlUtil.getRootElement(document003);
        Element YsPsdHead = XmlUtil.getElement(elementG,"HEAD");
        Element YsPsdMain = XmlUtil.getElement(elementG,"MAIN");
        YYq007 entity = yYq007Mapper.selectById(dto.getId());

        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的代填退货单号id:"+dto.getId().toString());
        }
        //判断订单编号是否已经更新
        if(StringUtils.isEmpty(entity.getThdbh()))
        {
            return JsonResult.error("代填退货单未上传，不能确认。");
        }
        String czlx = "1"; //新增
        String mac = "";
        String ip = NetUtil.getLocalhostStr();
        StringBuilder sb = new StringBuilder();
        String[] result = null;

        try {
            mac = NetUtil.getMacAddress(InetAddress.getLocalHost());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        CommonUtils.XmlSetNodeContent(YsPsdHead,"IP",ip);
        CommonUtils.XmlSetNodeContent(YsPsdHead,"MAC",mac.replaceAll(":","").replaceAll("-",""));
        CommonUtils.XmlSetNodeContent(YsPsdHead,"BZXX","");

        CommonUtils.XmlSetNodeContent(YsPsdMain,"YYBM",entity.getYybm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"YQBM",entity.getYqbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"PSDBM",entity.getPsdbm());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"DLCGBZ",entity.getDlcgbz());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"THSL",entity.getThsl().toString());
        CommonUtils.XmlSetNodeContent(YsPsdMain,"THDBH",entity.getThdbh());

        try {
            result = YsDDDTConfirm(XmlUtil.toStr(document003, true), entity.getThdbh());
            if ("00000".equals(result[4])) {
                return JsonResult.success();
            } else {
                return JsonResult.error(result[4]+result[5]+":"+result[6]);
            }
        }
        catch (Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    public String[] YsDDDTUpload(String YsXml, Integer id) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ007", YsXml);
        String ddmxbh = "";
        String ddbh = "";
        if ("00000".equals(rtnPsd[4]) || ("20000".equals(rtnPsd[4]) && rtnPsd[6].contains("已响应")))
        {
            //for (int i = 0; i < ddmxbhs.length; i++) {
            //更新订单响应类型
            //从返回结果xml报文中获取订单编号
            Document result = XmlUtil.readXML(rtnPsd[2]);
            Element elementG=XmlUtil.getRootElement(result);
            Element YsMain = XmlUtil.getElement(elementG,"MAIN");
            ddbh = CommonUtils.XmlGetNodeContent(YsMain,"THDBH");

            //更新药事平台返回的退货单编号
            UpdateWrapper<YYq007> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("thdbh",ddbh).set("status",1).eq("id",id);
            yYq007Mapper.update(new YYq007(),updateWrapper);
            //写入阳光配送单的日志
            SQLDBQuery.insertOrderTrackDetail(ddbh, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_07_01 + "," + "成功！");
            //}
        }

        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, ddbh, Const.YQ007_TXT);
        return rtnPsd;
    }

    public String[] YsDDDTConfirm(String YsXml, String ddbh) throws SQLException {
        //阳光配送单传报
        String[] rtnPsd = YsIntfce.SendYgRecv2019("YQ008", YsXml);
        String ddmxbh = "";
        if ("00000".equals(rtnPsd[4]) || ("20000".equals(rtnPsd[4]) && rtnPsd[6].contains("已响应")))
        {
            //for (int i = 0; i < ddmxbhs.length; i++) {
            //确认成功，更新状态为已确认
            //SQLDBQuery.updateYQ005Status(orderno,2);
            UpdateWrapper<YYq007> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status",2).eq("thdbh",ddbh);
            yYq007Mapper.update(new YYq007(),updateWrapper);
            //写入阳光配送单的日志
            SQLDBQuery.insertOrderTrackDetail(ddbh, Const.ORDER_03, DateUtil.now() +" "+ Const.ORDER_07_02 + "," + "成功！");
            //}
        }
        //写入传报及反馈日志
        SQLDBQuery.insertPostResultXml(rtnPsd, ddbh, Const.YQ008_TXT);
        return rtnPsd;
    }


    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(YYq007 entity) {
        entity.setUpdateUser(1);
        entity.setUpdateTime(DateUtils.now());
        entity.setMark(0);
        return super.delete(entity);
    }

    @Override
    public JsonResult deleteByIds(Integer[] ids) {
        try {
            for (Integer id : ids) {
                Map<String, Object> param = new HashMap<>();
                param.put("id", id);
                yYq007Mapper.deleteByMap(param);
            }
            return JsonResult.success();
        } catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }
}